<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>动态修改Python对象 | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="背景在Codewars上碰到一个很有趣的问题，和算法关系不大，主要是考究对Python对象的动态修改，题目描述是这样子的。
Description:For this kata you will be using some meta-programming magic to create a new Thing object. This object will allow you to define">
<meta property="og:type" content="article">
<meta property="og:title" content="动态修改Python对象">
<meta property="og:url" content="http://yoursite.com/2017/03/31/动态修改Python对象/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="背景在Codewars上碰到一个很有趣的问题，和算法关系不大，主要是考究对Python对象的动态修改，题目描述是这样子的。
Description:For this kata you will be using some meta-programming magic to create a new Thing object. This object will allow you to define">
<meta property="og:updated_time" content="2017-03-31T14:08:44.677Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="动态修改Python对象">
<meta name="twitter:description" content="背景在Codewars上碰到一个很有趣的问题，和算法关系不大，主要是考究对Python对象的动态修改，题目描述是这样子的。
Description:For this kata you will be using some meta-programming magic to create a new Thing object. This object will allow you to define">
  
    <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/css/style.css">
  

</head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-动态修改Python对象" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2017/03/31/动态修改Python对象/" class="article-date">
  <time datetime="2017-03-31T14:04:00.000Z" itemprop="datePublished">2017-03-31</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      动态修改Python对象
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h1 id="背景"><a href="#背景" class="headerlink" title="背景"></a>背景</h1><p>在Codewars上碰到一个很有趣的问题，和算法关系不大，主要是考究对Python对象的动态修改，题目描述是这样子的。</p>
<h2 id="Description"><a href="#Description" class="headerlink" title="Description:"></a>Description:</h2><p>For this kata you will be using some meta-programming magic to create a new Thing object. This object will allow you to define things in a descriptive sentence like format.</p>
<p>This challenge attempts to build on itself in an increasingly complex manner.</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line">jane = Thing('Jane')</div><div class="line">jane.name # =&gt; 'Jane'</div><div class="line"></div><div class="line"># can define boolean methods on an instance</div><div class="line">jane.is_a.person</div><div class="line">jane.is_a.woman</div><div class="line">jane.is_not_a.man</div><div class="line"></div><div class="line">jane.is_a_person # =&gt; True</div><div class="line">jane.is_a_man # =&gt; False</div><div class="line"></div><div class="line"># can define properties on a per instance level</div><div class="line">jane.is_the.parent_of.joe</div><div class="line">jane.parent_of # =&gt; 'joe'</div><div class="line"></div><div class="line"># can define number of child things</div><div class="line"># when more than 1, a tuple subclass is created</div><div class="line">jane.has(2).legs</div><div class="line">len(jane.legs) # =&gt; 2</div><div class="line">isinstance(jane.legs[0], Thing) # =&gt; True</div><div class="line"></div><div class="line"># can define single items</div><div class="line">jane.has(1).head</div><div class="line">isinstance(jane.head, Thing) # =&gt; True</div><div class="line"></div><div class="line"># can define number of things in a chainable and natural format</div><div class="line">&gt;&gt; Note: Python, unlike Ruby and Javascript, doesn't have a pretty syntax for blocks of expressions and a forEach method for iterables. So you should implement this behaviour yourself.</div><div class="line">jane.has(2).arms.each.having(1).hand.having(5).fingers</div><div class="line">len(jane.arms[0].hand.fingers) # =&gt; 5</div><div class="line"></div><div class="line"># can define properties on nested items</div><div class="line">jane.has(1).head.having(2).eyes.each.being_the.color.blue.having(1).pupil.being_the.color.black</div><div class="line"></div><div class="line"># can define methods: thing.can.verb(method, past='')</div><div class="line">method = lambda phrase: "%s says: %s" % (name, phrase)</div><div class="line"># or </div><div class="line">def method(phrase):</div><div class="line">  return "%s says: %s" % (name, phrase)</div><div class="line">jane.can.speak(method, "spoke")</div><div class="line"></div><div class="line">jane.speak("hello") # =&gt; "Jane says: hello"</div><div class="line"></div><div class="line"># if past tense was provided then method calls are tracked</div><div class="line">jane.spoke # =&gt; ["Jane says: hello"]</div></pre></td></tr></table></figure>
<h1 id="解析"><a href="#解析" class="headerlink" title="解析"></a>解析</h1><p>这个问题的关键是给现有对象添加新的属性，而属性的名字是不确定的，这时候一般要用到<strong>dict</strong>和重写<strong>getattr</strong>方法。</p>
<h1 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExtendTuple</span><span class="params">(tuple)</span>:</span></div><div class="line"><span class="string">""" 用来解决each的问题，因为要求访问tuple对象的each属性，所以写了一个tuple的拓展 """</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, *args, **kwargs)</span>:</span></div><div class="line">        super().__init__()</div><div class="line">        self.each = self[<span class="number">0</span>]</div><div class="line"></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Thing</span><span class="params">(object)</span>:</span></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, name, _type=<span class="string">'Thing'</span>, parent=None, number=<span class="number">0</span>)</span>:</span></div><div class="line">        self.name = name</div><div class="line">        self.type = _type</div><div class="line">        self.parent = parent</div><div class="line">        self.list = []</div><div class="line">        self.number = number</div><div class="line">        self.functions = &#123;&#125;</div><div class="line">        self.functions_called = &#123;&#125;</div><div class="line">        self.property = &#123;&#125;</div><div class="line">        <span class="keyword">if</span> self.type == <span class="string">'Thing'</span>:</div><div class="line">            self.being_a = self.is_a = Thing(<span class="string">'is_a'</span>, _type=<span class="string">'is_a'</span>, parent=self)</div><div class="line">            self.being_not_a = self.is_not_a = Thing(</div><div class="line">                <span class="string">'is_not_a'</span>, _type=<span class="string">'is_not_a'</span>, parent=self)</div><div class="line">            self.and_the = self.being_the = self.is_the = Thing(</div><div class="line">                <span class="string">'is_the'</span>, _type=<span class="string">'is_the'</span>, parent=self)</div><div class="line">            self.having = self.has</div><div class="line">            self.can = Thing(<span class="string">'can'</span>, _type=<span class="string">'can'</span>, parent=self)</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__getattr__</span><span class="params">(self, attr)</span>:</span></div><div class="line">        <span class="keyword">if</span> self.type <span class="keyword">in</span> (<span class="string">'is_a'</span>, <span class="string">'is_not_a'</span>, <span class="string">'being_a'</span>, <span class="string">'being_not_a'</span>):</div><div class="line">            self.list.append(attr)</div><div class="line">        <span class="keyword">elif</span> self.type <span class="keyword">in</span> (<span class="string">'is_the'</span>, <span class="string">'being_the'</span>, <span class="string">'and_the'</span>):</div><div class="line">            self.property[attr] = Thing(attr, _type=<span class="string">'property'</span>, parent=self)</div><div class="line">            <span class="keyword">return</span> self.property[attr]</div><div class="line">        <span class="keyword">elif</span> self.type == <span class="string">'property'</span>:</div><div class="line">            self.parent.parent.property[self.name] = attr</div><div class="line">            <span class="keyword">return</span> self.parent.parent</div><div class="line">        <span class="keyword">elif</span> self.type == <span class="string">'can'</span>:</div><div class="line">            <span class="function"><span class="keyword">def</span> <span class="title">func</span><span class="params">(func, name=<span class="string">''</span>)</span>:</span></div><div class="line">                self.parent.functions[attr] = (func, name)</div><div class="line">                self.parent.functions_called[name] = []</div><div class="line">            <span class="keyword">return</span> func</div><div class="line">        <span class="keyword">elif</span> self.type == <span class="string">'child'</span>:</div><div class="line">            <span class="keyword">if</span> self.number == <span class="number">1</span>:</div><div class="line">                self.parent.__dict__[attr] = Thing(attr)</div><div class="line">                self.parent.__dict__[attr].__dict__[<span class="string">'is_'</span> + attr] = <span class="keyword">True</span></div><div class="line">                <span class="keyword">return</span> self.parent.__dict__[attr]</div><div class="line">            <span class="keyword">else</span>:</div><div class="line">                one = Thing(attr[:<span class="number">-1</span>])</div><div class="line">                one.__dict__[<span class="string">'is_'</span> + attr[:<span class="number">-1</span>]] = <span class="keyword">True</span></div><div class="line">                self.parent.__dict__[attr] = ExtendTuple([one] * self.number)</div><div class="line">                <span class="keyword">return</span> self.parent.__dict__[attr]</div><div class="line">        <span class="keyword">elif</span> self.type == <span class="string">'Thing'</span>:</div><div class="line">            <span class="keyword">if</span> attr <span class="keyword">in</span> self.property:</div><div class="line">                <span class="keyword">return</span> self.property[attr]</div><div class="line">            <span class="keyword">if</span> attr <span class="keyword">in</span> self.functions:</div><div class="line">                <span class="function"><span class="keyword">def</span> <span class="title">actualfunc</span><span class="params">(*args, **kwargs)</span>:</span></div><div class="line">                    <span class="keyword">global</span> name</div><div class="line">                    name = self.name</div><div class="line">                    self.functions_called[self.functions[attr][<span class="number">1</span>]].append(</div><div class="line">                        self.functions[attr][<span class="number">0</span>](*args, **kwargs))</div><div class="line">                    <span class="keyword">return</span> self.functions_called[self.functions[attr][<span class="number">1</span>]][::<span class="number">-1</span>][<span class="number">0</span>]</div><div class="line">                <span class="keyword">return</span> actualfunc</div><div class="line">            <span class="keyword">elif</span> attr <span class="keyword">in</span> self.functions_called:</div><div class="line">                <span class="keyword">return</span> self.functions_called[attr]</div><div class="line">            <span class="keyword">elif</span> attr.startswith(<span class="string">'is_a_'</span>) <span class="keyword">or</span> attr.startswith(<span class="string">'being_a_'</span>):</div><div class="line">                name = attr.split(<span class="string">'a_'</span>)[<span class="number">1</span>]</div><div class="line">                <span class="keyword">if</span> name <span class="keyword">in</span> self.being_a.list:</div><div class="line">                    <span class="keyword">return</span> <span class="keyword">True</span></div><div class="line">                <span class="keyword">elif</span> name <span class="keyword">in</span> self.being_not_a.list:</div><div class="line">                    <span class="keyword">return</span> <span class="keyword">False</span></div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">has</span><span class="params">(self, number)</span>:</span></div><div class="line">        <span class="keyword">return</span> Thing(<span class="string">'has'</span>, _type=<span class="string">'child'</span>, parent=self, number=number)</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__repr__</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="keyword">return</span> <span class="string">'Thing (name = &#123;name&#125;)'</span>.format(name=self.name)</div></pre></td></tr></table></figure>
<h1 id="感想"><a href="#感想" class="headerlink" title="感想"></a>感想</h1><p>对Python对象来说，大胆地使用猴子补丁是没有什么问题的，只要能解决实际问题就可以，毕竟Python的对象本来就是对外暴露所有属性的。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2017/03/31/动态修改Python对象/" data-id="cj0xx7zpw0002rcule5vmjjrp" class="article-share-link">Share</a>
      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2017/03/31/Modern-C-现代C-中优雅的异步操作/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          [Modern C++]现代C++中优雅的异步操作
        
      </div>
    </a>
  
  
    <a href="/2017/03/31/hello-world/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">Hello World</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/03/">March 2017</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2017/03/31/【Python运维】最简单的Python运维脚本/">【Python运维】最简单的Python运维脚本Python运维】最简单的Python运维脚本</a>
          </li>
        
          <li>
            <a href="/2017/03/31/Modern-C-现代C-中优雅的异步操作/">[Modern C++]现代C++中优雅的异步操作</a>
          </li>
        
          <li>
            <a href="/2017/03/31/动态修改Python对象/">动态修改Python对象</a>
          </li>
        
          <li>
            <a href="/2017/03/31/hello-world/">Hello World</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2017 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/script.js"></script>

  </div>
</body>
</html>